const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user.model');
const asyncHandler = require('express-async-handler');
const auth = require('../middleware/auth');

// 用户注册
router.post('/register', asyncHandler(async (req, res) => {
  const { username, password, nickname } = req.body;

  // 检查用户是否已存在
  const existingUser = await User.findOne({ username });
  if (existingUser) {
    res.status(400);
    throw new Error('用户名已存在');
  }

  // 创建新用户
  const user = await User.create({
    username,
    password,
    nickname: nickname || username
  });

  // 生成token
  const token = jwt.sign(
    { id: user._id },
    process.env.JWT_SECRET || 'your-jwt-secret',
    { expiresIn: '30d' }
  );

  res.status(201).json({
    success: true,
    data: {
      id: user._id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      token
    }
  });
}));

// 用户登录
router.post('/login', asyncHandler(async (req, res) => {
  const { username, password } = req.body;

  // 查找用户
  const user = await User.findOne({ username });
  if (!user) {
    res.status(401);
    throw new Error('用户名或密码错误');
  }

  // 验证密码
  const isMatch = await user.comparePassword(password);
  if (!isMatch) {
    res.status(401);
    throw new Error('用户名或密码错误');
  }

  // 生成token
  const token = jwt.sign(
    { id: user._id },
    process.env.JWT_SECRET || 'your-jwt-secret',
    { expiresIn: '30d' }
  );

  res.json({
    success: true,
    data: {
      id: user._id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      gender: user.gender,
      birthday: user.birthday ,
      phone: user.phone,
      token
    }
  });
}));

// 获取当前用户信息
router.get('/me', auth, asyncHandler(async (req, res) => {
  const user = await User.findById(req.user._id).select('-password');
  if (!user) {
    res.status(404);
    throw new Error('用户不存在');
  }

  res.json({
    success: true,
    data: {
      id: user._id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      gender: user.gender,
      birthday: user.birthday ,
      phone: user.phone,
    }
  });
}));

// 更新用户信息
router.put('/update', auth, asyncHandler(async (req, res) => {
  const { nickname, avatar, gender, birthday, phone } = req.body;
  const user = await User.findById(req.user._id);

  if (!user) {
    res.status(404);
    throw new Error('用户不存在');
  }

  // 更新用户信息
  if (nickname) user.nickname = nickname;
  if (avatar) user.avatar = avatar;
  if (gender) user.gender = gender;
  if (birthday) user.birthday = birthday;
  if (phone) user.phone = phone;

  await user.save();

  res.json({
    success: true,
    data: {
      id: user._id,
      username: user.username,
      nickname: user.nickname,
      avatar: user.avatar,
      gender: user.gender,
      birthday: user.birthday ,
      phone: user.phone,
    }
  });
}));

// 验证token
router.post('/verify', auth, asyncHandler(async (req, res) => {
  res.json({
    success: true,
    valid: true,
    data: {
      id: req.user._id,
      username: req.user.username,
      nickname: req.user.nickname,
      avatar: req.user.avatar,
      gender: req.user.gender,
      birthday: req.user.birthday ,
      phone: req.user.phone,
    }
  });
}));

module.exports = router;